const lsPlugin = requirePlugin("lzbluetooth");
import api from '../../../api/index'

Page({
	/**
   * 页面的初始数据
   */
	data: {
		bindDeviceId: null,
		devicelist: [],
		showDevice: false,
		actions: [],
		bindDevice: [],
		saveDevice: {},
		showDialog: false,
		bindDeviceTextInfo: '',
		loading: false,
		currentDevice: null,
		timer: null,
		bleAvaible: true,
		saveDataList: []
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		this.initPlugin()
		this.get()
  },
  // 初始化插件
	initPlugin() {
		lsPlugin.init({
		  appId: "lx758d9d23a6bac221",
		  logger: null,
		  // 微信蓝牙开关回调
		  onBluetoothAdapterStateChange: (res) => {
			 if (res.available) {
				console.log('手环插件初始化成功')
				this.setData({
					bleAvaible: true
				})
			 } else {
				this.setData({
					bleAvaible: false
				})
				console.log(res, '手环插件初始化失败')
			 }
		  },
		})
	},
	// 链接设备
	goBindEq() {
		if(!this.data.bleAvaible) {
			wx.showToast({
				title: '蓝牙初始化失败',
				icon: 'none',
				duration: 2000
			})
			return
		}
		this.setData({
			bindDeviceTextInfo: '正在搜索蓝牙设备'
		})
		this.setData({
			showDialog: true
		})
		this.onScan()
		this.createTimeInter()
	},
	// 扫码设备
	onScan () {
		console.warn('--------------', '扫描')
		lsPlugin.startScanning(device => {
			 console.warn('发现设备', device)
			 // 判断是否存在A5
			 if (device.name.indexOf('HR6') > -1) {
				console.warn('发现HR6设备', device)
				this.setData({
					currentDevice: device
				})
				const actions =  [
					{ name: device.name, subname: device.deviceId, deviceId: device.deviceId, mac: device.mac},
				]
				this.setData({
					showDialog: false,
					actions: actions
				})
				// 搜索到可用的蓝牙设备，停止搜索
				this.stopScan()
				this.setData({ showDevice: true });
			 }
		})
	},
	// 未发现绑定，5秒再扫描一次
	createTimeInter() {
		this.data.timer = setInterval(() => {
		  if (!this.data.currentDevice) {
			 this.onScan()
		  } else {
			 this.stopScan()
		  }
		}, 5000)
	},
	// 停止扫描
	stopScan() {
		lsPlugin.stopScanning();
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		this.stopScan()
	},
	// 绑定设备
	onBind() {
		console.warn(this.data.saveDevice, '--------------开始绑定设备')
		this.setData({
			bindDeviceTextInfo: '正在绑定设备'
		})
		this.setData({
			showDialog: true
		})
		// 防止嵌套的缓存问题
		lsPlugin.bindDevice({
			mac: this.data.saveDevice.mac,
			callback: res => {
					console.warn('绑定设备结束', res)
					// 绑定成功
					if (res.bindState === 4) {
							this.doAddMonitorDevice()
							this.putData(this.data.saveDataList, '保存')
							this.setData({
								bindDeviceTextInfo: '设备绑定成功'
							})
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
							let pages=getCurrentPages();  //获取当前页面
							let beforePage=pages[pages.length-2]  //获取上一个页面的实例
							if(beforePage.onDataReport) {
								beforePage.onDataReport()
								beforePage.doAddMonitorDevice(this.data.saveDevice)
							}
							// 绑定失败
					} else if (res.bindState) {
						 console.log('绑定失败') 
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
					} else if (res?.errorCode) {
						 console.log('绑定失败') 
						 this.setData({
							bindDeviceTextInfo: '设备绑定失败'
						})
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
					} else {
						this.setData({
							bindDeviceTextInfo: '设备绑定失败'
						})
						setTimeout(() => {
							this.setData({
								showDialog: false,
							})
						}, 500);
					}
			}
		});
	},
	// 添加监听
	doAddMonitorDevice() {
		console.log(this.data.saveDevice,'this.data.saveDevice')
		lsPlugin.addMonitorDevice({ 
			mac: this.data.saveDevice.mac,
			model: this.data.saveDevice.model,
		})
	},
	onClose() {
    this.setData({ showDevice: false });
  },
	onSelect(event) {
		console.log(event.detail, 'event.detail')
		this.setData({
			saveDevice: event.detail
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name:this.data.saveDevice.name,deviceId: this.data.saveDevice.deviceId,mac: this.data.saveDevice.mac}
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.setData({
				saveDataList: saveDataList
			})
			// let pages=getCurrentPages();  //获取当前页面
			// let beforePage=pages[pages.length-2]  //获取上一个页面的实例
			// if(beforePage.onBind) {
			// 	this.setData({
			// 		showDialog: true,
			// 		bindDeviceTextInfo: '正在绑定设备'
			// 	})
			// 	beforePage.onBind(this.data.saveDevice).then(res => {
			// 		console.log('绑定成功了了了了了')
			// 		this.setData({
			// 			bindDeviceTextInfo: '设备绑定成功'
			// 		})
			// 		setTimeout(() => {
			// 			this.setData({
			// 				showDialog: false,
			// 			})
			// 		}, 500);
			// 		this.putData(this.data.saveDataList, '保存')
			// 	})
			// }
			this.onBind()
		}
  },
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'bracelet')
				if(listValue.length > 0) {
					this.setData({
						bindDevice: listValue[0].devicelist
					})
				}
		  }
			this.setData({
				loading: false
			})
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	doDeleteMonitorDevice(device) {
		console.log(device, '删除')
		lsPlugin.deleteMonitorDevice({ 
			mac: device.mac,
		})
	},
	delEq(e) {
		const name = e.currentTarget.dataset.name
		const data = this.data.bindDevice.filter(item => {
			return item.name !== name
		})
		const deldata = this.data.bindDevice.filter(item => {
			return item.name === name
		})
		this.doDeleteMonitorDevice(deldata[0])
		this.putData(data, '删除')
	},
	putData(deviceIdList, type) {
		let num = [{name:'bracelet',devicelist: deviceIdList}]
		num = JSON.stringify(num)
		this.doSavedevice(num, type)
	},
	// 储存设备
	async doSavedevice(result, type) {
		
		try {
		  await api.post('/api/user/storage/set', {
				data: {
					'key': 'devicelist',
					'value': result
				}
				})
				wx.showToast({
					title: `${type}成功`,
					icon: 'none',
					duration: 3000
				})
				this.setData({ showDevice: false });
				if(type!=='删除') {
					setTimeout(() => {
						wx.navigateBack({
							delta: 1 // 返回的页面数，1表示返回上一页
						});
					}, 1500);
				}
				this.get()
			} catch (e) {
				console.log('put->', e)
			}
	  },

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		clearInterval(this.data.timer)
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
